package web

import (
	"errors"
	"fmt"
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
	"jgt-oper/src/util"
	"time"
)

// UPEController 特殊人员授权区域管理
type UPEController struct {
	UserParkBll          *bll.UserParkBll     `inject:""`
	ParkBll              *bll.Park            `inject:""`
	ParkEntranceBll      *bll.ParkEntranceBll `inject:""`
	EntranceEquipmentBll *bll.EEBll           `inject:""`
}

// QueryPage 查询特殊授权区域人员的信息
func (a *UPEController) QueryPage(ctx *context.Context) error {
	ctx.WriteOperateLog("UPEController.QueryPage", "查询特殊人员门禁设备信息")

	var (
		params      *schema.UserEntranceParams
		total       int
		items       []*schema.ResponseItemUserEntrance
		err         error
		currentPage uint
		pageSize    uint
	)
	params = new(schema.UserEntranceParams)
	params.EnterpriseName = ctx.Query("enterprise_name")
	params.NickName = ctx.Query("nick_name")
	params.RealName = ctx.Query("real_name")
	params.ContractTel = ctx.Query("contract_tel")
	params.Gender = ctx.Query("gender")
	currentPage, pageSize = ctx.GetPageIndex(), ctx.GetPageSize()
	total, items, err = a.UserParkBll.QueryPage(params, currentPage, pageSize)
	fmt.Println(total, items, err)
	result := map[string]interface{}{
		"list": items,
		"pagination": map[string]interface{}{
			"total":    total,
			"current":  currentPage,
			"pageSize": pageSize,
		},
	}
	//测试
	temMap := make(map[int]interface{})
	for i := 0; i < 10; i++ {
		temMap[i] = i
	}
	key, _ := temMap[0]
	fmt.Println("key(0):", key)
	for value := range temMap {
		fmt.Println("value:", value)
	}

	return ctx.ResSuccess(result)
}

// QueryParkEntrance 根据授权区域列表查询对应的门禁设备列表
func (a *UPEController) QueryParkEntrance(ctx *context.Context) error {
	ctx.WriteOperateLog("UPEController.QueryParkEntrance", "查询区域对应的门禁设备")
	var (
		param                 *schema.QuerySpecialParkEntrance
		nodesAllowed          []string
		parkEntrances         []*schema.ParkEntrance
		entranceRecordIDArray []string
		entranceDetailArray   []*schema.EntranceEquipment
		temMap                map[string]interface{}
		err                   error
	)

	param = new(schema.QuerySpecialParkEntrance)
	if err = ctx.ParseJSON(param); err != nil {
		return ctx.ResErrBadRequest(err)
	}

	//授权区域的建筑节点
	nodesAllowed = make([]string, 0)
	for _, node := range param.ParkID {
		fatherNodes, err := a.ParkBll.QueryAllParentID(node, true)
		if err != nil {
			return ctx.ResErrBadRequest(err)
		}
		nodesAllowed = append(nodesAllowed, fatherNodes...)
	}
	//使用map去重
	temMap = make(map[string]interface{})
	for _, node := range nodesAllowed {
		temMap[node] = nil
	}
	nodesArrayQuery := make([]string, 0)
	for nodeQuery := range temMap {
		nodesArrayQuery = append(nodesArrayQuery, nodeQuery)
	}
	//授权区域建筑节点-门禁设备 的对应关系
	parkEntrances, err = a.ParkEntranceBll.GetByArray(nodesArrayQuery)
	if err != nil {
		return ctx.ResErrBadRequest(err)
	}
	//门禁设备record_id的列表
	entranceRecordIDArray = make([]string, 0)
	for _, parkEntrance := range parkEntrances {
		entranceRecordIDArray = append(entranceRecordIDArray, parkEntrance.Entrances...)
	}
	//对entranceRecordIDArray去重
	entranceIDArray := make([]string, 0)
	for _, entranceID := range entranceRecordIDArray {
		entranceIDArray = append(entranceIDArray, entranceID)
	}
	//	门禁详情列表
	entranceDetailArray, err = a.EntranceEquipmentBll.QueryEntranceArray(entranceIDArray)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	//	装配返回的map数组
	entranceMapArray := make([]map[string]interface{}, 0)
	for _, detail := range entranceDetailArray {
		tempMap := make(map[string]interface{})
		tempMap["entrance_id"] = detail.RecordID
		tempMap["equipment_id"] = detail.EquipmentID
		tempMap["equipment_name"] = detail.EquipmentName
		tempMap["equipment_type"] = detail.EquipmentType
		//	门禁设备管控的区域
		parkEntrances, err := a.ParkEntranceBll.GetByEntranceID(detail.RecordID)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		}
		//	构造管控区域名称
		tempMap["guard_zone"] = ""
		var guardZoneName string
		for _, parkEntrance := range parkEntrances {
			fullName, err := a.ParkBll.QueryFullName(parkEntrance.NodeID)
			if err != nil {
				return ctx.ResErrInternalServer(err)
			}
			guardZoneName += fullName
		}
		tempMap["guard_zone"] = guardZoneName

		tempMap["note"] = detail.Memo
		tempMap["state"] = "available"
		entranceMapArray = append(entranceMapArray, tempMap)
	}
	//	循环请求查询的门牌节点，构造列表用数据
	parkMapArray := make([]map[string]string, 0)
	for _, nodeID := range param.ParkID {
		allFatherNode, err := a.ParkBll.QueryAllParentNode(nodeID, true)
		if err != nil {
			return ctx.ResErrInternalServer(err)
		}
		tempMap := make(map[string]string)
		//	初始化数据
		tempMap["value"] = nodeID
		tempMap["key"] = nodeID
		tempMap["yuanqu"] = "-"
		tempMap["quyu"] = "-"
		tempMap["loudong"] = "-"
		tempMap["danyuan"] = "-"
		tempMap["louceng"] = "-"
		tempMap["menpai"] = "-"
		//	覆盖门牌名称
		for _, nodeItem := range allFatherNode {
			switch nodeItem.Type {
			case 10:
				tempMap["yuanqu"] = nodeItem.Name
			case 20:
				tempMap["quyu"] = nodeItem.Name
			case 30:
				tempMap["loudong"] = nodeItem.Name
			case 40:
				tempMap["danyuan"] = nodeItem.Name
			case 50:
				tempMap["louceng"] = nodeItem.Name
			case 60:
				tempMap["menpai"] = nodeItem.Name
			default:

			}
		}
		parkMapArray = append(parkMapArray, tempMap)
	}
	result := map[string]interface{}{
		"park_list":     parkMapArray,
		"entrance_list": entranceMapArray,
	}

	return ctx.ResSuccess(result)
}

// AddParkEntrance 保存授权区域和冻结的门禁设备
func (a *UPEController) AddParkEntrance(ctx *context.Context) error {
	ctx.WriteOperateLog("UPEController.AddParkEntrance", "保存区域对应的门禁设备")
	param := new(schema.ParamUserParkEntrance)
	if err := ctx.ParseJSON(param); err != nil {
		return ctx.ResErrBadRequest(err)
	}
	if param.OperateType == 1 {
		item := new(schema.SpecialUserPark)
		item.RecordID = util.UUID()
		item.UserID = param.UserID
		item.Parks = param.Parks
		item.EntrancesFrozen = param.EntrancesFrozen
		item.Creator = ctx.GetUserID()
		item.Created = time.Now().Unix()
		item.Deleted = 0

		err := a.UserParkBll.CreateParkEntrance(item)
		if err != nil {
			return ctx.ResErrBadRequest(err)
		}
	} else if param.OperateType == 2 {
		err := a.UserParkBll.UpdateParkEntrance(param)
		if err != nil {
			return ctx.ResErrBadRequest(err)
		}
	} else {
		return ctx.ResErrBadRequest(errors.New("operate_type错误"))
	}

	return ctx.ResOK()
}

// GetUserPark 查询特殊人员的授权区域
func (a *UPEController) GetUserPark(ctx *context.Context) error {
	ctx.WriteOperateLog("UPEController.GetUserPark", "获取用户授权区域和对应门禁设备关系")
	userID := ctx.Param("id")
	item, err := a.UserParkBll.GetUserPark(userID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(item)
}

// RemoveUserPark 删除授权区域
func (a *UPEController) RemoveUserPark(ctx *context.Context) error {
	ctx.WriteOperateLog("UPEController.RemoveUserPark", "删除特殊人员的授权相关信息")
	userID := ctx.Param("id")
	err := a.UserParkBll.RemoveUserPark(userID)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResOK()
}
